import getData from '../../service/getData.js'
import getData2 from '../../service/getData2.js'
import * as types from '../types'
import * as types1 from '../appendType'
import {Storage} from 'src/utils/storage.js'

export const coupon = {
  state: {
    couponTit: '',
    couponScreen: '',
    couponDistance: '',
    couponInfo: [],
    couponInfoPage: 1,
    couponInfoPageLimit: 10,
    searchKey: Storage.get('searchKey', true) || '',//搜索关键字
    searchType: 'mecth',//搜索电子券类型
    setOwnerInfo: {},//设置电子券拥有者信息
    couponDeatil: {},//电子券详情
    couponDetail: [],//优惠详情

    //关于电子券的评论
    couponComments: [],
    couponCommentsPage: 1,
    couponCommentsLimit: 10,
    //历史记录
    historyTag: [],//你可能在找
    historyList: Storage.get('history_info') || [],//搜索历史

    scroll: true, //避免快速滚动，无限拉取数据源
    //关于商户的评论
    shopComments: [],
    shopCommentsPage: 1,
    shopCommentsLimit: 10,
    //电子券用户评论详情
    couponComDetail: {},
    //用户经纬度
    position: Storage.get("sit", true) || '',
    //其他电子券
    otherPageLimit: 10,
    otherPageList: [],
    otherPage: 1,
    filterType: ''
  },
  actions: {
    /**
     * 猜你喜欢
     */
    guessLike({state, commit, rootState, getters}, params) {
      let page = {
        "aoData": "[{\"name\":\"iDisplayStart\",\"value\":" + state.couponInfoPage + "}," +
        "{\"name\":\"iDisplayLength\",\"value\":" + state.couponInfoPageLimit + "}]"
      };
      params.data = Object.assign(page, params.data);

      return new Promise(
        (resolve, reject) => {
          getData.guessLike(params, getters.userNum)
            .then(rep => {
              resolve(rep);
              if (rep.content.couponList) {//防止concat null
                commit(types.GET_COUPON_LIST, rep);
              }
              if (rep.content.couponList.length == 0) {
                return;
              }
              //state.couponInfoPage++;
            })
            .catch(rep => {
              reject(rep)
            })
        }
      );
    },
    /**
     * 餐饮分类
     */
    getFoodClass({state, commit, rootState, getters}, params) {
      params = Object.assign(params.data, {rows: state.couponInfoPageLimit, page: state.couponInfoPage});
      params.cityName = Storage.get('city', true)
      if (state.scroll) {
        commit(types.GET_SCORLL_STATUS, false);//避免快速滚动
        return new Promise(
          (resolve, reject) => {
            getData.foodClass({method: 'post', data: params})
              .then(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动

                resolve(rep);
                if (rep.content.couponList) {//防止concat null
                  commit(types.GET_COUPON_LIST, rep);
                }
                if (rep.content.couponList.length == 0) {
                  return;
                }
                commit(types.GET_PAGE_NUM);

              })
              .catch(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
                reject(rep)
              })

          }
        );
      }
    },
    /**
     * 电子券查询列表
     */
    getCouponList({state, commit, rootState, getters}, params) {
      params = Object.assign(params.data, {rows: state.couponInfoPageLimit, page: state.couponInfoPage});
      params.cityName = Storage.get('city', true)
      if(Storage.get('menuArrMess', true).menuArrId=='9008'){
      	params.flag=1
      }
      if (state.scroll) {
        commit(types.GET_SCORLL_STATUS, false);//避免快速滚动
        return new Promise(
          (resolve, reject) => {
            getData.couponList({method: 'post', data: params})
              .then(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
                resolve(rep);
                if (rep.content.couponList) {//防止concat null
                  commit(types.GET_COUPON_LIST, rep);
                }
                if (rep.content.couponList.length == 0) {
                  return;
                }
                commit(types.GET_PAGE_NUM);

              })
              .catch(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
                reject(rep)
              })

          }
        );
      }
    },
    /**
     * 商户查询列表
     */
    getMerList: function ({state, commit, rootState, getters}, params) {
      params = Object.assign(params.data, {rows: state.couponInfoPageLimit, page: state.couponInfoPage});
      params.cityName = Storage.get('city', true)
      if(Storage.get('menuArrMess', true).menuArrId=='9008'){
      	params.flag=1
      }
      if (state.scroll) {
        commit(types.GET_SCORLL_STATUS, false);//避免快速滚动
        return new Promise(
          (resolve, reject) => {
            getData.merList({method: 'post', data: params})
              .then(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动

                resolve(rep);
                if (rep.content.mchtList) {//防止concat null
                  commit(types.GET_MER_LIST, rep);
                }
                if (rep.content.mchtList.length == 0) {
                  return;
                }
                commit(types.GET_PAGE_NUM);

              })
              .catch(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
                reject(rep)
              })

          }
        );
      }
    },
    queryEightMcht: function ({state, commit, rootState, getters}, params) {
      params = Object.assign(params.data, {rows: state.couponInfoPageLimit, page: state.couponInfoPage});
      params.cityName = Storage.get('city', true)
      if (state.scroll) {
        commit(types.GET_SCORLL_STATUS, false);//避免快速滚动
        return new Promise(
          (resolve, reject) => {
            getData.queryEightMcht({method: 'post', data: params})
              .then(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动

                resolve(rep);
                if (rep.content.mchtList) {//防止concat null
                  commit(types.GET_MER_LIST, rep);
                }
                if (rep.content.mchtList.length == 0) {
                  return;
                }
                commit(types.GET_PAGE_NUM);

              })
              .catch(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
                reject(rep)
              })

          }
        );
      }
    },
    queryEight: function ({state, commit, rootState, getters}, params) {
      params = Object.assign(params.data, {rows: state.couponInfoPageLimit, page: state.couponInfoPage});
      params.cityName = Storage.get('city', true)
      if (state.scroll) {
        commit(types.GET_SCORLL_STATUS, false);//避免快速滚动
        return new Promise(
          (resolve, reject) => {
            getData2.queryEight({method: 'post', data: params})
              .then(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动

                resolve(rep);
                if (rep.content.couponList) {//防止concat null
                  commit(types.GET_COUPON_LIST, rep);
                }
                if (rep.content.couponList.length == 0) {
                  return;
                }
                commit(types.GET_PAGE_NUM);

              })
              .catch(rep => {
                commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
                reject(rep)
              })

          }
        );
      }
    },
    /**
     *推荐最优电子券
     */
    getRecCoupon({state, commit, rootState, getters}, params) {
      Object.assign(params.data, {rows: state.couponInfoPageLimit, page: state.couponInfoPage});
      return new Promise((resolve, reject) => {
        getData.recommendCoupon(params).then(rep => {
          resolve(rep)
          if (rep.content.couponList) {//防止concat null
            commit(types.get_rec_coupon, rep);
            state.couponInfoPage++
          }
        }).catch(rep => {
          reject()
        })
      })

    },
    /**
     *商户一类电子券
     */
    getOneCoupon({commit}, params) {
      return new Promise((resolve, reject) => {
        getData2.businessDiscount(params).then(rep => {
          resolve(rep)
          if (rep.content.couponList) {//防止concat null
            commit(types.get_one_coupon, rep);
            console.log(rep)
          }
        }).catch(rep => {
          reject()
        })
      })

    },
    /**
     *商户其他电子券
     */
    businessDiscount: function ({state, commit, rootState, getters}, params) {
      let page = {
        "aoData": "[{\"name\":\"iDisplayStart\",\"value\":" + state.otherPage + "}," +
        "{\"name\":\"iDisplayLength\",\"value\":" + state.otherPageLimit + "}]"
      };
      params.data = Object.assign(page, params.data);
      return new Promise((resolve, reject) => {
        getData2.businessOrder(params).then(function (rep) {
          resolve(rep);
          if (rep.respCode == "00") {

            commit(types1.OTHER, rep);
            if (rep.content.couponList.length == 0) {
              return;
            }
            state.otherPage++;
          }
        }).catch(function (rep) {
          reject(rep)
        });

      });
    },
    //电子券详情
    couponDetail: function ({commit}, params) {
      return new Promise(
        (resolve, reject) => {
          getData.couponDetail(params)
            .then(rep => {
              resolve(rep);
              // state.couponDeatil = rep.content.coupon;
              commit(types.COUPON_DETAIL, rep);
            })
            .catch(rep => {
              reject(rep)
            })
        }
      );
    },
    //电子券评论列表
    couponComments: function ({state, commit, rootState}, params) {
      let page = {
        "aoData": "[{\"name\":\"iDisplayStart\",\"value\":" + state.couponCommentsPage + "}," +
        "{\"name\":\"iDisplayLength\",\"value\":" + state.couponCommentsLimit + "}]"
      };
      params.data = Object.assign(page, params.data);
      return new Promise((resolve, reject) => {
        if (rootState.coupon.scroll) {
          commit(types.GET_SCORLL_STATUS, false);//避免快速滚动
          getData.couponComments({method: 'post', couponId: params.couponId, mchtId: params.mchtId, data: params.data})
            .then(rep => {
              commit(types.GET_SCORLL_STATUS, true);//避免快速滚动
              resolve(rep);
              // if(rep.content.commList){
              //     commit(types.COUPON_COMMENTS, rep);
              // }
              // if(rep.content.commList.length == 0){
              //     return;
              // }
              // state.couponCommentsPage++;
              if (rep.respCode == "00") {
                commit(types.COUPON_COMMENTS, rep);
                if (rep.content.commList.length == 0) {
                  return;
                }
                state.couponCommentsPage++;
              }

            }).catch(rep => {
            reject(rep)
          });
        }
      });

    },
    //关于商户的评论列表
    shopComments: function ({state, commit}, params) {
      let page = {
        "aoData": "[{\"name\":\"iDisplayStart\",\"value\":" + state.couponCommentsPage + "}," +
        "{\"name\":\"iDisplayLength\",\"value\":" + state.couponCommentsLimit + "}]"
      };
      params.data = Object.assign(page, params.data);
      return new Promise(
        (resolve, reject) => {
          getData.shopComments({method: 'post', mchtId: params.mchtId, data: params.data})
            .then(rep => {
              commit(types.GET_SCORLL_STATUS, true);
              resolve(rep);
              // if(rep.content.commList){
              //     commit(types.SHOP_COMMENTS, rep);
              // }
              // if(rep.content.commList.length == 0) {
              //     return;
              // }
              // state.couponCommentsPage++;
              if (rep.respCode == "00") {
                commit(types.SHOP_COMMENTS, rep);
                if (rep.content.commList.length == 0) {
                  return;
                }
                state.couponCommentsPage++;
              }

            })
            .catch(rep => {
              reject(rep)
            })

        }
      );
    },
    //电子券用户评论详情
    couponCommentDetail: function ({commit}, params) {

      return new Promise(
        (resolve, reject) => {
          getData2.couponCommentDetail({method: 'post', usrId: params.usrId, commId: params.commId})
            .then(rep => {
              resolve(rep);
              commit(types.COUPON_COM_DETAIL, rep);
            })
            .catch(rep => {
              reject(rep)
            })
        }
      );
    },
    //电子券商户评论详情
    shopCommentDetail: function ({commit}, params) {
      return new Promise(
        (resolve, reject) => {
          getData2.shopCommentDetail({method: 'post', mchtId: params.mchtId, commId: params.commId})
            .then(rep => {
              resolve(rep);
              commit(types.SHOP_COM_DETAIL, rep);
            })
            .catch(rep => {
              reject(rep)
            })
        }
      );
    }

  },
  mutations: {
    // 电子券筛选
    couponScreenChoose(state, screening) {
      state.couponScreen = screening
    },
    // 电子券距离筛选
    couponDistanceChoose(state, distance) {
      state.couponDistance = distance;
    },
    [types.filter_type](state, res) {
      state.filterType = res;
    },
    //电子券列表
    [types.GET_COUPON_LIST](state, res) {
      if (!res) {
        state.couponInfo = [];
        return;
      }
      if (state.couponInfoPage <= 1) {
        state.couponInfo = []
        state.couponInfo = res.content.couponList
//              var newArr=[];
// function _objIsInArray(obj,arr){
//   let tmpStatus=false;
//   for(let j=0;j<arr.length;j++){
//     if((obj.mchtId==arr[j].mchtId)&&(obj.usrId==arr[j].usrId)&&(obj.couponId==arr[j].couponId)){
//       return j;
//       break;
//     }else{
//       tmpStatus=false;
//     }
//   }
//   if(!tmpStatus){
//     return -1;
//   }
// }
// for(let i=0;i<state.couponInfo.length;i++){
//   if(_objIsInArray(state.couponInfo[i],newArr) ==-1){
//      newArr.push(state.couponInfo[i]);
//   }else{
//     console.log('对象已存在');
//   }
// }
// state.couponInfo=newArr                    
      } else {
        state.couponInfo = state.couponInfo.concat(res.content.couponList)
//                            var newArr=[];
// function _objIsInArray(obj,arr){
//   let tmpStatus=false;
//   for(let j=0;j<arr.length;j++){
//     if((obj.mchtId==arr[j].mchtId)&&(obj.usrId==arr[j].usrId)&&(obj.couponId==arr[j].couponId)){
//       return j;
//       break;
//     }else{
//       tmpStatus=false;
//     }
//   }
//   if(!tmpStatus){
//     return -1;
//   }
// }
// for(let i=0;i<state.couponInfo.length;i++){
//   if(_objIsInArray(state.couponInfo[i],newArr) ==-1){
//      newArr.push(state.couponInfo[i]);
//   }else{
//     console.log('对象已存在');
//   }
// }
// state.couponInfo=newArr
      }
    },
    // [types.GET_SEARCH_KEY](state, params) {
    //     state.searchKey = params
    // },
    [types.GET_PAGE_NUM](state, num) {
      if (num) {
        state.couponInfoPage = num;
        return;
      }
      state.couponInfoPage += 1
    },
    [types.GET_SCORLL_STATUS](state, status) {
      state.scroll = status
    },
    //商户列表
    [types.GET_MER_LIST](state, res) {
      if (!res) {
        state.couponInfo = [];
        return;
      }

      if (state.couponInfoPage <= 1) {
        state.couponInfo = res.content.mchtList
      } else {
        state.couponInfo = state.couponInfo.concat(res.content.mchtList)
      }
    },
    //获取最优电子券
    [types.get_rec_coupon](state, res) {
      if (!res) {
        state.couponInfo = [];
        return;
      }
      if (state.couponInfoPage <= 1) {
        state.couponInfo = res.content.couponList
      } else {
        state.couponInfo = state.couponInfo.concat(res.content.couponList)
      }

    },
    //获取一类电子券
    [types.get_one_coupon](state, res) {

      if (!res) {
        state.couponInfo = [];
        return;
      }
      state.couponInfo = res.content.couponList

    },
    //电子券评论列表
    [types.COUPON_COMMENTS](state, rep) {
      if (!rep) {
        state.couponComments = [];
        return;
      }
      for (var i = rep.content.commList.length - 1; i >= 0; i--) {
        if (rep.content.commList[i].replyDsc) {
          if (rep.content.commList[i].replyDsc.length > 3) {
            rep.content.commList[i].replyDsc.length = 3;
          }
        }
      }
      ;
      if (state.couponCommentsPage <= 1) {
        state.couponComments = rep.content.commList
      } else {
        state.couponComments = state.couponComments.concat(rep.content.commList)
      }

    },
    [types.COUPON_PAGES](state) {
      state.couponCommentsPage = 1;
    },
    //设置电子券拥有者信息
    [types.coupon_owner_info](state, param) {
      state.setOwnerInfo = param;
    },
    //设置搜索关键字
    [types.search_key](state, key) {
      Storage.set('searchKey', key, true)
      state.searchKey = Storage.get('searchKey', true);
    },
    //设置搜索类型
    [types.search_type](state, type) {
      // 保存搜索类型
      state.searchType = type;
    },
    //设置搜索标题
    [types.coupon_tit](state, str) {
      state.couponTit = str;
    },
    /**
     * 历史记录
     */
    [types.set_history_tag](state, str) {
      state.historyTag.push(str);
      state.historyTag = Array.from(new Set(state.historyTag));
    },
    [types.history_info](state, param) {
      state.historyList = param;
    },
    //关于商户的评论
    [types.SHOP_COMMENTS](state, rep) {
      // console.log(rep);
      if (!rep) {
        state.shopComments = [];
        return;
      }
      var imgStrs = [];
      for (var i = rep.content.commList.length - 1; i >= 0; i--) {
        if (rep.content.commList[i].commPicUrl) {

          imgStrs = rep.content.commList[i].commPicUrl.split(",");
          // imgStrs.length=imgStrs.length-1;
          rep.content.commList[i].commPicUrl = imgStrs;
          // console.log(rep.content.commList[i].commPicUrl)
        }
        if (rep.content.commList[i].replyDsc) {
          if (rep.content.commList[i].replyDsc.length > 3) {
            rep.content.commList[i].replyDsc.length = 3;
          }
        }
      }
      if (state.couponCommentsPage <= 1) {
        state.shopComments = rep.content.commList
      } else {
        state.shopComments = state.shopComments.concat(rep.content.commList)
      }
      ;
      // for (var i = rep.content.commList.length - 1; i >= 0; i--) {
      //     if (rep.content.commList[i].replyDsc.length>3) {
      //         rep.content.commList[i].replyDsc.length=3;
      //     }
      // };


    },
    // 订单详情
    [types.COUPON_DETAIL](state, rep) {
      state.couponDetail = rep.content.coupon;
    },
    //电子券用户评论详情
    [types.COUPON_COM_DETAIL](state, rep) {
      state.couponComDetail = rep.content;
    },
    [types.usr_position](state, str) {
      Storage.set("sit", str, true);
      state.position = str;
    },

    //商户其他电子券
    [types1.OTHER](state, rep) {
      if (!rep) {
        state.otherPageList = [];
        return
      }
      if (state.otherPage <= 1) {
        state.otherPageList = rep.content.couponList;
      } else {
        state.otherPageList = state.otherPageList.concat(rep.content.couponList);
      }
    },
    //商户其他电子券分页
    [types1.OTHER_PAGE](state, num) {
      state.otherPage = num;
    },
  },
  getters: {
    position: state => state.coupon.position
  }
}
